﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Wpf.Common;
using Wpf.SharedContracts;
using WpfApp1.Chat.UserPage;

namespace WpfApp1.Chat
{
    /// <summary>
    /// Layout.xaml 的交互逻辑
    /// </summary>
    public partial class Layout : Window
    {
        private const string PipeName = "SocketToWpfPipe";
        private CancellationTokenSource _cts;
        public Layout()
        {
            InitializeComponent();

            MainFrame.Navigate(new WelcomePage());

            this.Loaded += Layout_Loaded;

            StartPipeClient();
        }

        private async void Layout_Loaded(object sender, RoutedEventArgs e)
        {
            // 连接到 WebSocket 服务器
            await WebSocketHelper.WebSocketInit();
        }

        private void SideMenu_SelectionChanged(object sender, HandyControl.Data.FunctionEventArgs<object> e)
        {
            var name = e.Info.GetType().GetProperty("Name").GetValue(e.Info).ToString();
            if (name == "page1")
            {
                MainFrame.Navigate(new HomePage());
            }

        }

        private BitmapImage Base64ToBitmapImage(string base64String)
        {

            byte[] imageBytes = Convert.FromBase64String(base64String);

            using (var memoryStream = new MemoryStream(imageBytes))
            {
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.StreamSource = memoryStream;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }

        private void StartPipeClient()
        {
            _cts = new CancellationTokenSource();
            Task.Run(() => ListenToPipe(_cts.Token), _cts.Token);
        }

        private async Task ListenToPipe(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                try
                {
                    using (var client = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
                    {
                        await client.ConnectAsync(token);

                        // 使用 MemoryStream 动态接收管道数据
                        using (var ms = new MemoryStream())
                        {
                            var buffer = new byte[8192]; // 8 KB 分块
                            int bytesRead;

                            // 循环读取直到管道关闭或没有更多数据
                            while ((bytesRead = await client.ReadAsync(buffer, 0, buffer.Length, token)) > 0)
                            {
                                ms.Write(buffer, 0, bytesRead);

                                // 可根据你的协议判断完整消息
                                // 如果每次发送一条 JSON，可以在发送端加 \n 或其他分隔符
                                if (ms.Length > 0 && ms.ToArray()[ms.Length - 1] == (byte)'\n')
                                {
                                    break; // 读到一条完整消息
                                }
                            }

                            if (ms.Length == 0) continue; // 没有数据则继续循环

                            // 将字节流转换为字符串
                            string messageJson = Encoding.UTF8.GetString(ms.ToArray()).Trim();

                            // 移除可能的换行符
                            messageJson = messageJson.TrimEnd('\r', '\n');

                            // 反序列化
                            var message = JsonSerializer.Deserialize<PipeMessage>(messageJson);

                            if (message != null)
                            {
                                // 更新 UI（确保在主线程）
                                Dispatcher.Invoke(() =>
                                {
                                    MyImage.Source = Base64ToBitmapImage(message.Data);
                                });
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // 正常退出
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() => MessageBox.Show($"管道错误: {ex.Message}"));
                }
            }
        }

    }
}
